package com.linuxgt.demo.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author liuteng
 * @time Created on 2018-05-04 下午3:13.
 */
@RestController
public class RedisController {
    private static final Logger log = LoggerFactory.getLogger(RedisController.class);
    private final String GROUP = "test";
    private final String KEY = "count";
    private final CacheManager cacheManager;

    @Autowired
    public RedisController(CacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }

    @GetMapping("/hello")
    public void sayHello() {
        log.info("hello spring boot redis");
    }

    @GetMapping("/count")
    public int count() {
        Cache.ValueWrapper valueWrapper = this.cacheManager.getCache(GROUP).get(KEY);
        return valueWrapper == null ? -1 : (int) valueWrapper.get();
    }

    @PostMapping("/add")
    public void add() {
        if (this.cacheManager.getCache(GROUP).get(KEY) == null) {
            this.cacheManager.getCache(GROUP).put(KEY, 0);
        }
        int curr = (int) this.cacheManager.getCache(GROUP).get(KEY).get();
        this.cacheManager.getCache(GROUP).put(KEY, curr + 1);
        log.info("count:{}", curr);
    }
}
